package com.own.component.sms.aliyun.util;

import com.alibaba.fastjson2.JSON;
import com.own.component.common.exception.BusinessException;
import com.own.component.sms.aliyun.property.SmsAliyunProperty;
import com.own.component.sms.core.base.BaseSmsSendService;
import com.own.component.sms.core.em.SmsSendMethodEnum;
import com.own.component.sms.core.model.SmsSendModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * AliyunSmsSendUtil
 *
 * @author chenxueli
 * @date 2023-06-28 16:24:00
 */
@Slf4j
@Component
public class AliyunSmsSendUtil implements BaseSmsSendService {

    @Resource
    private SmsAliyunProperty smsAliyunProperty;

    private com.aliyun.dysmsapi20170525.Client client;

    /**
     * 获取客户端信息
     *
     * @return 客户端信息
     */
    private com.aliyun.dysmsapi20170525.Client createClient() {
        if (client != null) {
            return client;
        }
        var config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(smsAliyunProperty.getKey())
                .setAccessKeySecret(smsAliyunProperty.getSecret());
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        try {
            client = new com.aliyun.dysmsapi20170525.Client(config);
            return client;
        } catch (Exception e) {
            throw new BusinessException("创建阿里云短信客户端失败", e);
        }
    }

    /**
     * 发送信息
     *
     * @param model 发送的模型信息
     */
    @Override
    public void send(SmsSendModel model) {
        var client = createClient();
        var request = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                .setPhoneNumbers(String.join(",", model.getPhoneList()))
                .setSignName(smsAliyunProperty.getSignName())
                .setTemplateCode(model.getTemplateId())
                .setTemplateParam(JSON.toJSONString(model.getParamMap()));
        var runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            var response = client.sendSmsWithOptions(request, runtime);
            var code = response.getBody().getCode();
            if (!"OK".equals(code)) {
                throw new BusinessException("发送短信失败：" + response.getBody().getMessage());
            }
        } catch (Exception e) {
            throw new BusinessException("发送短信失败", e);
        }
    }

    /**
     * 类型名称
     *
     * @return 类型名称
     */
    @Override
    public SmsSendMethodEnum type() {
        return SmsSendMethodEnum.ALIYUN;
    }

}
